<template>
    <div>
        <ul>
            <li v-for="(item, index) in sortedItems" :key="index">
                {{ item.name }} - 价格: {{ item.price }}, 数量: {{ item.quantity }}, 总价: {{ calculateTotal(item) }}
                <button @click="incrementQuantity(index)">+</button>
                <button @click="decrementQuantity(index)">-</button>
            </li>
        </ul>
        <div>
            总计: {{ totalPrice }}
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue';

// 定义对象数组
const items = ref([
    { name: 'Item 1', price: 10.5, quantity: 1 },
    { name: 'Item 2', price: 20.75, quantity: 2 },
    { name: 'Item 3', price: 30.99, quantity: 3 }
]);

// 自增数量函数
const incrementQuantity = (index) => {
    items.value[index].quantity++;
};

// 自减数量函数
const decrementQuantity = (index) => {
    if (items.value[index].quantity > 0) {
        items.value[index].quantity--;
    }
};

// 计算单个项目的总价并保留小数点后两位
const calculateTotal = (item) => {
    return (item.price * item.quantity).toFixed(2);
};

// 计算所有项目的总价
const totalPrice = computed(() => {
    let sum = 0;
    items.value.forEach(item => {
        sum += item.price * item.quantity;
    });
    return sum.toFixed(2);
});

// 按总价排序的项目列表
const sortedItems = computed(() => {
    return [...items.value].sort((a, b) => {
        return (b.price * b.quantity) - (a.price * a.quantity);
    });
});
</script>

<style scoped>
/* 添加一些简单的样式 */
ul {
    list-style-type: none;
}

li {
    margin: 5px 0;
}

button {
    margin-left: 10px;
}
</style>
